package cz.zcu.fav.rat.managed.validator;

import javax.faces.application.FacesMessage;
import javax.faces.component.UIComponent;
import javax.faces.component.UIInput;
import javax.faces.context.FacesContext;
import javax.faces.validator.FacesValidator;
import javax.faces.validator.Validator;
import javax.faces.validator.ValidatorException;

import org.apache.commons.codec.digest.DigestUtils;

import cz.zcu.fav.rat.beans.User;
import cz.zcu.fav.rat.dataaccess.service.UserService;
import cz.zcu.fav.rat.managed.bean.SpringBeanFactory;
import cz.zcu.fav.rat.managed.locale.LocaleMessageFactory;

@FacesValidator(value = "changemypassvalidator")
public class ChangeMyPassValidator implements Validator
{

	@Override
	public void validate(FacesContext arg0, UIComponent component, Object arg2)
			throws ValidatorException
	{
		UIInput oldPwdInput = (UIInput) component.getAttributes().get("oldpwd");

		Integer id = (Integer) component.getAttributes().get("usrid");
		String oldpasshash = DigestUtils.md5Hex((String) oldPwdInput
				.getSubmittedValue());

		UserService service = SpringBeanFactory.getInstance().getBean(
				"userService", UserService.class);
		User user = service.get(id);

		if (!user.getPasshash().equals(oldpasshash))
		{
			String message = LocaleMessageFactory
					.getLocale("view.objectcreate.error.wrongoldpass");

			oldPwdInput.setValid(false);
			FacesMessage msg = new FacesMessage(FacesMessage.SEVERITY_ERROR,
					message, null);

			throw new ValidatorException(msg);
		}

	}

}
